//
//  ST_BaseWebController.m
//  ST_BaseMall
//
//  Created by 昱胜 on 2022/9/2.
//

#import "ST_BaseWebController.h"
#import "HNSH_CashierPayViewController.h"
#import "HNSH_ExchangeViewController.h"

@interface ST_BaseWebController ()<WKScriptMessageHandler>

/* URLString */
@property(nonatomic, copy) NSString *URLString;

@end

@implementation ST_BaseWebController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.webView.wkWebView.configuration.userContentController addScriptMessageHandler:self name:@"toCashier"];
    
    [self.webView.wkWebView.configuration.userContentController addScriptMessageHandler:self name:@"getToken"];
    [self.webView.wkWebView.configuration.userContentController addScriptMessageHandler:self name:@"getClientInfo"];
    [self.webView.wkWebView.configuration.userContentController addScriptMessageHandler:self name:@"goBack"];
    [self.webView.wkWebView.configuration.userContentController addScriptMessageHandler:self name:@"toAwardRecord"];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    // 这里要记得移除handlers
    [self.webView.wkWebView.configuration.userContentController removeScriptMessageHandlerForName:@"toCashier"];
    
    [self.webView.wkWebView.configuration.userContentController removeScriptMessageHandlerForName:@"getToken"];
    [self.webView.wkWebView.configuration.userContentController removeScriptMessageHandlerForName:@"getClientInfo"];
    [self.webView.wkWebView.configuration.userContentController removeScriptMessageHandlerForName:@"goBack"];
    [self.webView.wkWebView.configuration.userContentController removeScriptMessageHandlerForName:@"toAwardRecord"];
    
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self deleteWebCache];
}

//WKScriptMessageHandler协议方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    // message.body 即为JS向OC传的值
    id body = message.body;
    NSLog(@"=== %@", body);
    if ([message.name isEqualToString:@"toCashier"]) {//前往收银台
        HNSH_CashierPayModel *model = [HNSH_CashierPayModel yy_modelWithDictionary:body];
        HNSH_CashierPayViewController * vc = [HNSH_CashierPayViewController new];
        vc.fromWeb = YES;
        vc.payModel = model;
        [[UIViewControllerHelper findCurrentShowingViewController].navigationController pushViewController:vc animated:YES];
    } else if ([message.name isEqualToString:@"getToken"]) {//获取token
        [self sendMessageToJSFromNme:@"toWebToken" data:[NSString stringWithFormat:@"bearer %@",[ST_UserManager shareInstance].access_token]];
    } else if ([message.name isEqualToString:@"getClientInfo"]) {//获取ClientInfo
        [self sendMessageToJSFromNme:@"toWebClientInfo" data:[ST_BaseNetManager getClientInfo]];
    } else if ([message.name isEqualToString:@"goBack"]) {//返回按钮
        [self goBack];
    } else if ([message.name isEqualToString:@"toAwardRecord"]) {//前往获奖记录页面
        ST_BaseWebController *web = [[ST_BaseWebController alloc]init];
        [web loadURLString:k_user_lbzq_record];
        [self.navigationController pushViewController:web animated:YES];
    }
}


// ----------------- 给前端发消息 -------------------------
-(void)sendMessageToJSFromNme:(NSString *)name data:(id)data
{
    NSString * jsStr = [NSString stringWithFormat:@"%@('%@')",name,data];
    NSLog(@"jsStr ==> %@",jsStr);
    [self.webView.wkWebView evaluateJavaScript:jsStr completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        if (!error) {
            NSLog(@"成功 = %@",response);
        } else {
            NSLog(@"失败 = %@",error.localizedDescription);
        }
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createContentView];
    [self showNavTitle:self.titleString showLeftItem:YES];
    [self createNav];
}

- (void)setIsHiddenNav:(BOOL)isHiddenNav {
    _isHiddenNav = isHiddenNav;
}

#pragma mark - 控件初始化
-(ST_ProgressWKWebView *)webView
{
    if (_webView == nil) {
        _webView = [[ST_ProgressWKWebView alloc] init];
        _webView.backgroundColor = [UIColor appBGColor];
        _webView.delegate = self;
        [_webView setProgressTintColor:[UIColor appWhiteLabelColor] TrackColor:[UIColor colorWithRGB:0xffeecc]];
    }
    return _webView;
}


#pragma mark - 界面初始化
-(void)createNav
{

    [self.webView.wkWebView addObserver:self forKeyPath:@"canGoBack" options:NSKeyValueObservingOptionNew context:(__bridge void * _Nullable)([self class])];
    self.navView.hidden = self.isHiddenNav;
    WeakSelf(weakSelf);
    self.navView.leftBlock = ^{
        if (weakSelf.isClose) {
            [super goBack];
        } else {
            [weakSelf goBack];
        }
    };
//    //加个右边空白显示的按钮
//    UIButton *right1Btn = [[UIButton alloc] initWithFrame:(CGRect){0,0,40,40}];
//    UIBarButtonItem * right1Item = [[UIBarButtonItem alloc] initWithCustomView:right1Btn];
//    self.navigationItem.rightBarButtonItem = right1Item;
    
}

-(void)createContentView
{
    [self.view addSubview:self.webView];
    if (self.isHiddenNav) {
        [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
        }];
    } else {
        [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(UIEdgeInsetsMake(kNavBarAndStatusBarHeight, 0, 0, 0));
        }];
    }
}

#pragma mark - 监控
- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context
{
    if([keyPath isEqualToString:@"canGoBack"])
    {
        [self showNavTitle:self.title backItem:self.webView.wkWebView.canGoBack];
    }
}
- (void)goBack{
    if ([self.webView.wkWebView canGoBack]) {
        [self.webView.wkWebView goBack];
    } else
    {
        if (self.fromWeb) {
            [self.navigationController popToViewController:self.navigationController.viewControllers[self.navigationController.viewControllers.count-4] animated:YES];
        } else {
            [super goBack];
        }
    }
}
#pragma mark - 外部接口
- (void)loadRequest:(NSURLRequest *)request
{
    [self.webView loadRequest:request];
}

- (void)loadURL:(NSURL *)URL {
    [self.webView loadRequest:[NSURLRequest requestWithURL:URL]];
}

- (void)loadURLString:(NSString *)URLString {
    if(!URLString.length)
    {
        return;
    }
    _URLString = URLString;
   [self isNeedGetTicketWithUrlStr:URLString];
}
- (void)loadHTMLString:(NSString *)HTMLString{
    [self loadHTMLString:HTMLString baseURL:nil];
}
- (void)loadHTMLString:(NSString *)HTMLString baseURL:(NSURL *)baseURL{
    [self.webView.wkWebView loadHTMLString:HTMLString baseURL:baseURL];
}
- (void)loadFileURL:(NSURL *)loadFileURL allowingReadAccessToURL:(NSURL *)allowingReadAccessToURL{
    [self.webView.wkWebView loadFileURL:loadFileURL allowingReadAccessToURL:allowingReadAccessToURL];
}


//TODO: 判断是否需要登录操作
-(void)isNeedGetTicketWithUrlStr:(NSString *)urlStr
{
    NSURL *URL = [NSURL URLWithString:urlStr];
    [self.webView loadURL:URL];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

-(void)dealloc
{
    //[self.webView.wkWebView removeObserver:self forKeyPath:@"canGoBack"];
}

- (void)deleteWebCache {
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0) {
        NSSet *websiteDataTypes = [NSSet setWithArray:@[WKWebsiteDataTypeDiskCache,
                                                        //WKWebsiteDataTypeOfflineWebApplicationCache,
                                                        WKWebsiteDataTypeMemoryCache,
                                                        //WKWebsiteDataTypeLocalStorage,
                                                        //WKWebsiteDataTypeCookies,
                                                        //WKWebsiteDataTypeSessionStorage,
                                                        //WKWebsiteDataTypeIndexedDBDatabases,
                                                        //WKWebsiteDataTypeWebSQLDatabases
                                                      ]];
        //// All kinds of data
        /////NSSet *websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];
        /////// Date from
        NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
        //// Execute
        [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
            // Done
        }];
    } else {
        NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSString *cookiesFolderPath = [libraryPath stringByAppendingString:@"/Cookies"];
        NSError *errors;
        [[NSFileManager defaultManager] removeItemAtPath:cookiesFolderPath error:&errors];
    }
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
    return NO ;
}
@end
